package com.bp.hearthealth.pulse.lnapps.firbase

import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.BuildConfig
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsCount
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_utils.SpUtils
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.firebase.FirebaseApp
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.remoteconfig.ConfigUpdate
import com.google.firebase.remoteconfig.ConfigUpdateListener
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.google.firebase.remoteconfig.FirebaseRemoteConfigException
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings
import com.google.gson.Gson

object FireBaseUtils {

    private var mDefaultConfigMap: Map<String, String>? = null
    private var firebaseSucess = true
    fun init() {
        listener?.notReady()
        FirebaseApp.initializeApp(BpApplication.context)
        val mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance()
        val configSettings = FirebaseRemoteConfigSettings.Builder()
            .setMinimumFetchIntervalInSeconds((if (BuildConfig.DEBUG) 300 else 60 * 30).toLong()) //3600
            .build()
        mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings)
        // 设置应用内默认值, 异步设置的. 约300ms生效
        //firebase_remote_config_defaults
        mFirebaseRemoteConfig.setDefaultsAsync(R.xml.firebase_remote_config_defaults)
            .addOnCompleteListener(OnCompleteListener<Void?> { task: Task<Void?>? ->
                LogUtil.i("Firebase setDefaultsAsync(R.xml.firebase_remote_config_defaults)结果: ${task?.isSuccessful}")
            })
        mFirebaseRemoteConfig.fetchAndActivate().addOnCompleteListener { task: Task<Boolean> ->
            //Task true如果当前调用激活了获取的配置，则会产生结果；如果获取的配置已被先前的调用激活，则它会返回一个Task结果false。
            if (task.isSuccessful) {
                //firebase激活成功事件
                AppsFlyerUtils.trackEvent("firebase_get_success")
                val updated = task.result
                if (updated) {
                    //第一次安装 updated为true
                    AdsCount.initDate()
                    LogUtil.i("Firebase 激活成功 第一次安装")
                } else {
                    //不是第一次安装 update为false
                    LogUtil.i("Firebase 激活成功 不是第一次安装")
                }
                listener?.successful(true)
            } else {
                LogUtil.i("Firebase task.isSuccessful = false")
                initLocal()
            }
        }

        FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
            if (!task.isSuccessful) {
                return@addOnCompleteListener
            }
            LogUtil.i("firebase token.result: ${task.result}")
        }

        mFirebaseRemoteConfig.addOnConfigUpdateListener(object : ConfigUpdateListener {
            override fun onUpdate(configUpdate: ConfigUpdate) {
                LogUtil.i("Updated keys: " + configUpdate.updatedKeys);
                //welcome_message  后台更新字段
                val updatedKeys = configUpdate.updatedKeys
                if (updatedKeys.contains(AdsSwitch.adAppControl) //总开关
                    || updatedKeys.contains(AdsSwitch.adOpenControl)//开屏广告总开关
                    || updatedKeys.contains(AdsSwitch.adInterControl)//插页广告总开关
                    || updatedKeys.contains(AdsSwitch.adNativeControl)//原生广告总开关
                    || updatedKeys.contains(AdsSwitch.adRVControl)//激励广告总开关
                    || updatedKeys.contains(AdsSwitch.adBannerControl)//横幅广告总开关
                    || updatedKeys.contains(AdsSwitch.adNativeLanguage)//语言选择页屏幕底部_大原生广告位
                    || updatedKeys.contains(AdsSwitch.adNativeGender)//性别选择页功能栏下方_原生广告
                    || updatedKeys.contains(AdsSwitch.adInterLaunchGender)//第一次启动性别选择页后_插页广告
                    || updatedKeys.contains(AdsSwitch.adOpenLaunch)//第一次冷启动后_开屏广告
                    || updatedKeys.contains(AdsSwitch.bp_rv_cd_s)//激励视频解锁倒计时时间
                    || updatedKeys.contains(AdsSwitch.userDailyMaxAdsClickNum)//用户每日最大广告点击数量
                    || updatedKeys.contains(AdsSwitch.userDailyMaxVideoAdsShowNum)//用户每日最大全屏（开屏/插页/激励）广告展示数量
                    || updatedKeys.contains(AdsSwitch.adInterLaunchIntro)//第一次启动引导Guide页后_插页广告
                    || updatedKeys.contains(AdsSwitch.adNativeBPResult)//血压结果页原生广告位
                    || updatedKeys.contains(AdsSwitch.adNativeHRReport)//心率报告页原生广告位
                    || updatedKeys.contains(AdsSwitch.adInterCacheControl)//是否缓存插页广告
                ) {
                    mFirebaseRemoteConfig.activate().addOnCompleteListener {
                        AdsCount.initDate(true)
                    }
                }
            }

            override fun onError(error: FirebaseRemoteConfigException) {
                LogUtil.i("Config update error with code: " + error.code, error)
            }
        })
        //测试数据
//        firebaseSucess = false
        //获取本地默认数据
//        initLocal()
    }

    private fun initLocal() {
        firebaseSucess = false
        mDefaultConfigMap = FirebaseDefaultsXmlParser.getDefaultsFromXml(
            BpApplication.context, R.xml.firebase_remote_config_defaults
        )
        LogUtil.i("Firebase 激活失败")
        AdsCount.initDate()
        listener?.successful(getBoolean(AdsSwitch.adOpenLaunch))
    }

    fun getString(key: String): String? {
        if (!firebaseSucess) {
            return mDefaultConfigMap?.get(key)
        }
        return FirebaseRemoteConfig.getInstance().getString(key)
    }

    fun getBoolean(key: String): Boolean {
        //今天
        if (AdsCount.isToday()) {
            //今天 & 本地存储了广告开关
            if (!SpUtils.getBoolean(AdsSwitch.adAppControl)) {
                return false
            }
        }
        if (!firebaseSucess) {
            return mDefaultConfigMap?.get(key).toBoolean()
        }
        return FirebaseRemoteConfig.getInstance().getBoolean(key)
    }

    fun getLong(key: String): Long {
//        return mDefaultConfigMap?.get(key)?.toLong()!!
        return FirebaseRemoteConfig.getInstance().getLong(key)
    }

    fun getDouble(key: String): Double {
//        return mDefaultConfigMap?.get(key)?.toDouble()!!
        return FirebaseRemoteConfig.getInstance().getDouble(key)
    }

    fun <T> getJson(key: String, tClass: Class<T>?): T {
//        return Gson().fromJson(mDefaultConfigMap?.get(key), tClass)
        return Gson().fromJson(FirebaseRemoteConfig.getInstance().getString(key), tClass)
    }

    interface FetchConfigCompleteCallback {
        fun successful(var1: Boolean)
        fun notReady()
    }

    private var listener: FetchConfigCompleteCallback? = null
    fun setFetchConfigCompleteCallback(listener: FetchConfigCompleteCallback?) {
        this.listener = listener
    }
}

